<template>
    <div class="app-container">
          <template>
            用户URL图片列表  

    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <!-- <el-form-item>
        <el-input v-model="pictureQuery.username" placeholder="讲师名"/>
      </el-form-item> -->

      <!-- <el-form-item>
        <el-select v-model="pictureQuery.level" clearable placeholder="讲师头衔">
          <el-option :value="1" label="高级讲师"/>
          <el-option :value="2" label="首席讲师"/>
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-input v-model="pictureQuery.originalFilename" placeholder="原文件名"/>
      </el-form-item>

      <el-form-item label="添加时间">
        <el-date-picker
          v-model="pictureQuery.begin"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="pictureQuery.end"
          type="datetime"
          placeholder="选择截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" @click="getList()">查询</el-button>
      <el-button type="default" @click="resetData()">清空</el-button>
    </el-form>
          <el-button  type="warning" icon="el-icon-delete" class="btn-add" @click="batchRemove()" round>批量删除</el-button>

          <!-- <el-button :loading="loading" type="success" @click="downCom()" round>
                保真批量下载
                <i class="icon-down"></i>
          </el-button> -->
          
          <el-button  type="success" icon="el-icon-delete" class="btn-add" @click="handleBatchDownload()" round>批量下载</el-button>
        <!-- 表格 -->
    <el-table
      :data="list"
      border
      fit
      @selection-change="handleSelectionChange"
      highlight-current-row>
<el-table-column type="selection"/>
      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>


<!-- todo   -->
      <!-- <el-table-column
        label="头像"
        align="center">
<div class="demo-image__placeholder">
  <div class="block">
    <span class="demonstration">默认</span>
    <el-image :src="scope.row.avatar" ></el-image>
  </div>
</div>
</el-table-column> -->



        <el-table-column label="图片预览" width="120" >
                <template slot-scope="scope" v-if="scope.row.newFilename">
                    <img :src="scope.row.newFilename" preview="1" width="80%" height="80%" class="avatar"/>
                </template>

            </el-table-column>



      <!-- <el-table-column prop="userId" label="用户名称" width="100" /> -->


      <!-- <el-table-column label="课程状态" width="80">
        <template slot-scope="scope"> -->
            <!-- ===表示匹配类型和值 -->
            <!-- {{findUserNameByUserId(scope.row.userId) }} -->
          <!-- {{ scope.row.userId===2?'已发布':'未发布' }}
        </template>
      </el-table-column> -->
       <!-- <el-table-column prop="username" label="用户名称" width="120" /> -->

       <el-table-column prop="originalFilename" label="原文件名称" width="120" />





      <!-- <el-table-column prop="intro" label="资历"  width="200" /> -->

    

      <el-table-column prop="gmtCreate" label="添加时间" width="160"/>

      <!-- <el-table-column prop="sort" label="排序" width="60" /> -->

      <el-table-column label="操作" width="200px" align="center">
        <template slot-scope="scope">
          <div>
      <el-button class="bar_btn copy_btn" :data-clipboard-text="auditReson" type="primary" size="mini"  icon="el-icon-document-copy"   style="width:120px;margin-bottom:30px;" @click="copy(scope.row.newFilename)"  round>复制URL地址</el-button>      
      </div>
      <div>
      <el-button type="danger" size="mini"  icon="el-icon-delete"   style="width:120px;margin-bottom:30px;" @click="removeDataById(scope.row.pid)"  round>删除</el-button>
      </div>
            <!-- <el-button :loading="loading" type="primary" style="width:30%;margin-bottom:30px;" @click="register">注册</el-button> -->
      
      <!-- <a href="/register">注册</a> -->
      
        </template>
      </el-table-column>
    </el-table>
     <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="getList"
    />
  </template>
    </div>
</template>
<script>
// import userApi from '@/api/dfs/user'
// npm install clipboard --save
import { mapGetters } from 'vuex'
import Clipboard from 'clipboard';//复制配件
import pictureApi from '@/api/dfs/picture'

import JSZip from 'jszip'
import FileSaver from "file-saver"
// 下面为下载组件
import axios from 'axios'
 const getFile = url => {
 return new Promise((resolve, reject) => {
  axios({
  method:'get',
  url,
  responseType: 'arraybuffer'
 }).then(data => {
  resolve(data.data)
 }).catch(error => {
  reject(error.toString())
 })
 })
}

export default {
    computed: {
    ...mapGetters([
      'name'
    ])
  },
    //写核心代码位置
    data(){
        return {
            list:[],
            loading: false,
            page:1,
            limit:10,
            total:0,
            pictureQuery:{},
            multipleSelection: [],
            tableData:[],
            auditReson:"",
            idList:[],
            arr2:[],
            imgNameList:[],
        }
    },
    created(){
        this.getList(this.page)
        // this.findAllUser()
    },
    methods:{
    //   findUserNameByUserId(id){
    //     		for (var i = 0; i < this.tableData.length; i++) {
    //           if (id==this.tableData[i].UserId)
    //           //console.log("this.tableData[i]")
    //           return this.tableData[i].username; 
		// }
    //   }
    //   ,
      // findAllUser(){//查询user
      //     userApi.findAll().then(response=>{//请求成功
      //     debugger
      //     // this.tableData = response.data
      //     console.log(response.data)
      //     for (var i = 0; i < response.data.length; i++) {
      //       this.tableData.push("userId",response.data[i].UserId)
      //       this.tableData.push("username",response.data[i].username)
      //     }
      //     console.log("tableData"+this.tableData)
      //     console.log(this.tableData)
      //     }).catch(error =>{//请求失败
      //           console.log("请求失败:"+error)
      //       })
      // },
        //列表方法
        getList(page = 1){
          // aeert
          // this.pictureQuery.username=`admin`
            this.page = page
            this.pictureQuery.username=this.name
            pictureApi.listByUserId(this.page,this.limit,this.pictureQuery)
            .then(response=>{//请求成功
            // response接口返回的数据
                // console.log(response)
                this.list = response.data.records
                this.total = response.data.total
                 console.log(this.list)  
                //  console.log(this.total) ;
                // alert(this.page)
            })
            .catch(error =>{//请求失败
                console.log("请求失败:"+error)
            })
        }
        ,
        resetData() {//清空的方法
            //表单输入项数据清空
            this.pictureQuery = {}
            //查询所有讲师数据
            this.getList(this.page)
        }
        ,
        removeDataById(id){
             this.$confirm('此操作将永久删除图片记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
             pictureApi.removeById(id)
            .then(response=>{//请求成功
                this.$message({
                     type: 'success',
                     message: '删除成功!'
                })
                this.getList(this.page)
            })
        })
        },
        //复制图片链接地址
       copy(file) {
                this.auditReson = file
        var clipboard = new Clipboard(".copy_btn");
        
        // alert(this.auditReson)
        clipboard.on("success", () => {
          this.$message.success('复制成功~')

          // 释放内存
          clipboard.destroy();
        });

        clipboard.on("error", () => {
          // 不支持复制
          this.$message.error('复制失败，请重试')
          // 释放内存
          clipboard.destroy();
        });
      },
        
        // 当多选选项发生变化的时候调用
        handleSelectionChange(selection) {
          console.log(selection)
          this.multipleSelection = selection
        },


                // 批量删除
        batchRemove() {
          if (this.multipleSelection.length === 0) {
            this.$message.warning('请选择要删除的记录！')
            return
          }
          //alert(this.multipleSelection[0].pid)
          this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 点击确定，远程调用ajax
            // 遍历selection，将id取出放入id列表

           this.idList = []
            this.multipleSelection.forEach(item => {
              // alert(item.pid)
              // alert(item.originalFilename)
              this.idList.push(item.pid)
            })
            alert("idList:"+this.idList)
            // 调用api.batchRemove
            return pictureApi.batchRemove(this.idList)
          }).then((response) => {
            // this.idList=[]
            this.getList()
            this.$message.success(response.message)
          }).catch(error => {
            if (error === 'cancel') {
              this.$message.info('取消删除')
            }
          })
        },
        //批量下载======================================测试一号========================================
        downCom(){
          // this.downIamge("http://192.168.56.10:9000/youmans/youmans_1666100869960.jpg")
          // this.downloadByBlob("http://192.168.56.10:9000/youmans/youmans_1666100869960.jpg","pic")
          this.downImg()
        },

         downloadByBlob(url,name) {
          let image = new Image()
          image.setAttribute('crossOrigin', 'anonymous')
          image.src = url
          image.onload = () => {
            let canvas = document.createElement('canvas')
            canvas.width = image.width
            canvas.height = image.height
            let ctx = canvas.getContext('d')
          ctx.drawImage(image,0,0, image.width, image.height)
          canvas.toBlob((blob) => {
            let url = URL.createObjectURL(blob)
            this.download(url,name)
            alert(url)
            // 用完释放URL对象
            URL.revokeObjectURL(url)
          })
        }
      },
      
        download(href, name) {  
          let eleLink = document.createElement('a')
          eleLink.download = name
          eleLink.href = href
          eleLink.click()
          eleLink.remove()
          alert(href)
      },
      ////批量下载======================================测试二号适合单个下载========================================
                              downIamge(imgsrc) {
                            let that = this;
                            var img = document.createElement('img');
                            // img.crossOrigin = "*"; //跨域1
                            // img.crossOrigin = ""; //跨域2
                            img.src = imgsrc + '?v=' + Math.random();//清除图片缓存
                            img.crossOrigin = 'anonymous';//跨域3
                            img.onload = function() {
                              let dataURL = that.getBase64Image(img);
                              let aLink = window.document.createElement('a');
                              let blob = that.base64ToBlob(dataURL);
                              let evt = document.createEvent('HTMLEvents');
                              evt.initEvent('click', true, true);
                              aLink.download = new Date().getTime() + '.png';//下载图片名称/类型可更改
                              aLink.href = URL.createObjectURL(blob);
                              aLink.click();
                            };
                          },
                          getBase64Image(img) {
                            let canvas = document.createElement('canvas'); // 创建一个canvas
                            canvas.width = img.width; // 设置对应的宽高
                            canvas.height = img.height;
                            let ctx = canvas.getContext('2d'); // 二维绘图环境
                            ctx.drawImage(img, 0, 0, img.width, img.height); // 将图片画在画布上
                            let dataURL = canvas.toDataURL('image/png'); // 得到base64 编码的 dataURL
                            return dataURL;
                          },
                          // 这里把图片转base64
                          base64ToBlob(code) {
                            // alert(code);
                            let parts = code.split(';base64,');
                            // alert(parts[1]);
                            let contentType = parts[0].split(':')[1];
                            let raw = window.atob(parts[1]);
                            let rawLength = raw.length;
                            let uInt8Array = new Uint8Array(rawLength);
                            for (let i = 0; i < rawLength; ++i) {
                              uInt8Array[i] = raw.charCodeAt(i);
                            }
                            return new Blob([uInt8Array], { type: contentType });
                          },
        //  ================================三批量打包下载  下载的文件为源文件============================================ 
           
          async downImg(){
              //按钮禁用防止重复点击
               this.downImg2()
                  // this.loading=false  
                  setTimeout(() => {
                  this.loading=false  
                  location. reload()
              }, 6000)
            },

            downImg2() {

                   if (this.multipleSelection.length === 0) {
                    this.$message.warning('请选择要下载的记录！')
                    return
                  }
                  this.loading = true
                    // this.arr = []
                    //获取数据源
                    this.idList = []
                    // alert(arr)
                    var imgNameList=[]
                    this.multipleSelection.forEach(item => {
                      //alert(item.newFilename)
                      // alert(item.pid)
                      // alert(item.originalFilename)
                      this.arr2.push(item.newFilename)
                      imgNameList.push(item.originalFilename)
                      // this.idList.push(item.pid)
                    })



                  var blogTitle = '批量图片包';
                  var zip = new JSZip();
                  var imgs = zip.folder(blogTitle);
                  var baseList = [];
                  // 要下载图片的url
                  // var arr = ['http://192.168.56.10:9000/youmans/youmans_1666100869960.jpg', 'http://192.168.56.10:9000/youmans/youmans_1666100869960.jpg', 'http://192.168.56.10:9000/youmans/youmans_1666100869960.jpg'];
                  // 下载后图片的文件名，个数应与arr对应
                  var arr = this.arr2
                    //alert(arr)
                  //var imgNameList = ['图片1', '图片2', '图片3'];
          
                  for (var i = 0; i < arr.length; i++) {
                      let image = new Image();
                      // 解决跨域 Canvas 污染问题
                      image.setAttribute('crossOrigin', 'anonymous');
                      
                      image.onload = function () {
                          let canvas = document.createElement('canvas');
                          canvas.width = image.width;
                          canvas.height = image.height;
                          
                          let context = canvas.getContext('2d');
                          context.drawImage(image, 0, 0, image.width, image.height);
                          
                          let url = canvas.toDataURL(); // 得到图片的base64编码数据
                          canvas.toDataURL('image/png');
                          
                          baseList.push(url.substring(22));    // 去掉base64编码前的 data:image/png;base64,
                          if (baseList.length === arr.length && baseList.length > 0) {
                              for (let k = 0; k < baseList.length; k++) {
                                  imgs.file(imgNameList[k], baseList[k], {base64: true})
                              }
                              zip.generateAsync({type: 'blob'}).then(function (content) {
                                  // see FileSaver.js
                                  FileSaver.saveAs(content, blogTitle + '.zip');
                              });
                          }
          
                      };
                      image.src = arr[i];
                  }
                  // this.loading = false
              },
            //   datecrol(){
            //   //定时任务方法
            // this.$nextTick(() => {
            // setInterval(this.next, 3000);
            //   });
            // }

// ======================批量下载4 下载的图片失真为压缩图======================
      handleBatchDownload() {
             if (this.multipleSelection.length === 0) {
            this.$message.warning('请选择要下载的记录！')
            return
          }
                      var imgNameList=[]
                       this.multipleSelection.forEach(item => {
                      //alert(item.newFilename)
                      // alert(item.pid)
                      // alert(item.originalFilename)
                      this.arr2.push(item.newFilename)
                      imgNameList.push(item.originalFilename)
                      // this.idList.push(item.pid)
                    })
        // const data = ['http://192.168.56.10:9000/youmans/2022-10-26/youmans_1666795582284.jpg', 'http://192.168.56.10:9000/youmans/2022-10-26/youmans_1666795602505.jpg'] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
        const data =this.arr2
        const zip = new JSZip()
        const cache = {}
        const promises = []
        data.forEach(item => {
        const promise = getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
        const arr_name = item.split("/")
        //  alert(data.length)
        const file_name = arr_name[arr_name.length - 1] // 获取文件名
        //  const file_name = imgNameList[this.indexs]
        //   this.indexs=this.indexs+1
          zip.file(file_name, data, { binary: true }) // 逐个添加文件
        cache[file_name] = data
        })
        promises.push(promise)
        })
      
        Promise.all(promises).then(() => {
        zip.generateAsync({type:"blob"}).then(content => { // 生成二进制流
        FileSaver.saveAs(content, "图片包.zip") // 利用file-saver保存文件
        })
        })
      },


    }
}
</script>